package com.logistics.controller;

import com.logistics.pojo.Result;
import com.logistics.pojo.Admin;
import com.logistics.service.AdminService;
import com.logistics.utils.JwtUtil;
import com.logistics.utils.Md5Util;
import com.logistics.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    //注册功能
    @PostMapping("/register")
    public Result register(String adminname, String password) {
        //查询用户(判断是否已有)
        Admin u = adminService.findByAdminName(adminname);
        if (u == null) {
            //用户不存在
            //注册
            adminService.register(adminname, password);
            return Result.success();
        } else {
            //已存在
            return Result.error("用户名已被占用");
        }
    }

    //登录功能
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{4,16}$") String adminname, @Pattern(regexp = "^\\S{4,16}$") String password ){

        //根据用户名查询用户
        Admin loginAdmin = adminService.findByAdminName(adminname);
        System.out.println(loginAdmin.getPassword());
        if(loginAdmin==null){
            return Result.error("用户名不存在");
        }

        //判断传入的密码与查询到的密码是否一致
        if(Md5Util.getMD5String(password).equals(loginAdmin.getPassword())){
            //登录成功(返回一个token令牌)
            Map<String, Object> claims = new HashMap<>();
            //将当前使用者id和username放入token中
            claims.put("id", loginAdmin.getId());
            claims.put("username", loginAdmin.getAdminname());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);//将token返回给浏览器
        }
//        if(Md5Util.getMD5String(adminpassword).equals(loginAdmin.getAdminpassword())){
//
//        }
        return Result.error("密码错误");
    }

    //获取用户详细信息
//获取用户详细信息(已登录的用户的id和username信息放在token里面）
    @GetMapping("/userInfo")
    public Result<Admin> userInfo(/*@RequestHeader(name = "Authorization") String token*/) {
        //根据用户名查询用户
//        Map<String, Object> map = JwtUtil.parseToken(token);
//        String username = (String) map.get("username");
        //有了线程后，不需要在从请求头中获取token业务数据了，直接从线程中拿
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        Admin user = adminService.findByAdminName(username);
        return Result.success(user);
    }
}
